'use strict';

const Controller = require('egg').Controller;

class WmsController extends Controller {
  async hscode() {
    // /posts/:id	post
    // put 方式更新
    const { ctx } = this;
    const id = ctx.params.id;
    if (!id) {
      ctx.state = 403;
      ctx.body = { code: 403, msg: '参数不正确！' };
      return;
    }

    const jsdom = require('jsdom');
    const jquery = require('jquery');
    const sync = require('xd-synchttp'); // 同步HTTP请求库
    const content = sync.http_get(`http://kw.hscode.net/AI/AIHscodeDetail?hscode=${id}`, 0);
    const { document } = (new jsdom.JSDOM(content)).window;
    const $ = jquery(document.defaultView);
    const [ result, field, value ] = [{}, [], []];

    $('.details').find('tr').each(function() {
      const tr1 = $(this);
      tr1.find('th').each(function() {
        const _this = $(this);
        field.push(_this.text());
      });
      tr1.find('td').each(function() {
        const _this = $(this);
        value.push(_this.text());
      });
    });

    field.forEach((f, index) => {
      result[f] = value[index] === '-' ? '' : value[index];
    });

    let [ field2, value2 ] = [];
    $('.details').find('h3').each(function() {
      if (!field2) field2 = $(this).text();
    });
    $('.details').find('.pd20').each(function() {
      if (!value2) value2 = $(this).text();
    });
    // 格式化字符串形式的申报要素为JSON数组。
    value2 = value2.split(';');
    const newValue2 = [];
    value2.forEach(v => {
      const json = {};
      if (v) {
        const j = v.split(':');
        json[j[0]] = j[1] ? j[1] : '';
        newValue2.push(json);
      }
    });
    result[field2] = newValue2;

    ctx.set('Content-Type', 'application/json');
    if (!result) {
      ctx.state = 403;
      ctx.body = { code: 403, msg: '参数不正确！' };
    } else {
      ctx.state = 200;
      ctx.body = { code: 200, data: result };
    }
  }

  async checkWareHouseBillCodeState() { // 检查报关单的放行状态，通过单一窗口获取数据。
    const { ctx } = this;
    const cid = ctx.params.id;
    if (!cid) {
      ctx.state = 403;
      ctx.body = { code: 403, msg: '参数不正确！' };
      return;
    }

    const request = require('request');
    const iconv = require('iconv-lite');
    const url = 'http://exp.szcport.cn:8282/NEWabl/entryInfoQuery.action?queryBean1.queryInput1=' + cid;
    const querystring = require('querystring');
    const data = querystring.stringify({
      'queryBean1.queryInput1': cid,
    });
    const opt = {
      url,
      hostname: 'exp.szcport.cn',
      port: 8282,
      path: '/NEWabl/entryInfoQuery.action',
      method: 'POST',
      headers: {
        Connection: 'keep-alive',
        'Content-Length': data.length,
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'User-Agent': 'Mozilla/5.0 (Linux; Android 5.0; SM-N9100 Build/LRX21V) > AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 > Chrome/37.0.0.0 Mobile Safari/537.36 > MicroMessenger/6.0.2.56_r958800.520 NetType/WIFI',
      }, // 伪造请求头
    };

    function callApi(arg) {
      return new Promise(function(resolve, reject) {
        request(arg).pipe(iconv.decodeStream('gbk')).collect(function(err, decodedBody) {
          if (err) {
            ctx.state = 403;
            ctx.body = { code: 403, msg: err };
          } else if (decodedBody) {
            const jsdom = require('jsdom');
            const jquery = require('jquery');
            const { document } = (new jsdom.JSDOM(decodedBody)).window;
            const $ = jquery(document.defaultView);
            const $rs = $('.companyName');
            const $noerr = $('.norecordNew');
            const $err = $('.norecord');
            if ($err.length > 0) {
              const state = $err.html();
              reject(state);
            } else if ($noerr.length > 0) {
              const state = $noerr.html();
              reject(state);
            } else {
              const state = $rs.attr('title');
              resolve(state);
            }
          }
        });
      });
    }

    try {
      const res = await callApi(opt);
      ctx.state = 200;
      ctx.body = { code: 200, data: res };
    } catch (error) {
      ctx.state = 403;
      ctx.body = { code: 403, msg: error };
    }
  }
}

module.exports = WmsController;
